package com.sendpo.zjx.sendpo.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchatsmianDynimcDomain;
import com.sendpo.zjx.sendpo.fragment.storeallproduce.SendActiveFragment;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.imagewatcher.ImageWatcher;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 朱俊鑫 on 2018
 */

public class MerchatsmainDynmicListActivity extends AppCompatActivity {

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.fabu_bt)
    RelativeLayout fabuBt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.v_image_watcher)
    ImageWatcher vImageWatcher;
    @BindView(R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;
    LinearLayoutManager lm;
    private RecylcerAdaper adpter;
  private  int pagenow=1;
    private int merchantsId=0;
   public static  final int FINSIH=1001;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchatsmaindynmic);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        merchantsId=getIntent().getIntExtra("merchantsId",0);
        initComponent();

    }
    private void initComponent() {
        lm=new LinearLayoutManager(this, OrientationHelper.VERTICAL,false);
        recyclerview.setLayoutManager(lm);
        List<MerchatsmianDynimcDomain.DataBean> dataBeans=new ArrayList<>();
        recyclerview.setAdapter(adpter=new RecylcerAdaper(dataBeans,this));
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pagenow=1;
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    query(pagenow,merchantsId,0);
                }else{
                    query(pagenow,merchantsId,userList.get(0).getUserId());
                }
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pagenow++;
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    append(pagenow,merchantsId,0);
                }else{
                    append(pagenow,merchantsId,userList.get(0).getUserId());
                }
            }
        });
        pulltofresh.autoRefresh();
    }

    @OnClick(value = {R.id.backbt,R.id.fabu_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.fabu_bt:
                Intent intent=new Intent(this,MerchantDynmicSubmitActivity.class);
                intent.putExtra("merchantsId",merchantsId);
                startActivityForResult(intent,FINSIH);
                break;
        }
    }
    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerchatsmianDynimcDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<MerchatsmianDynimcDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_juagesendpo_item, parent, false));
            return ih;
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final MerchatsmianDynimcDomain.DataBean dataBean=dataBeen.get(position);
            ih.all_ll.removeAllViews();
            List<String> imgs = dataBean.getMerchantsDyImgsPath();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(MerchatsmainDynmicListActivity.this);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(100), DensityUtil.dip2px(100));
                    lp.setMargins(0, 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(MerchatsmainDynmicListActivity.this)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    ih.all_ll.addView(iv);
                }
            }
            if(dataBean.isDynamicpraiseState()){
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
            }else{
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);

            }
            ih.goods_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<User> userList= Xutils.queryAll(MerchatsmainDynmicListActivity.this.getApplication(),User.class);
                    if(userList==null||userList.size()==0){
                        Tools.redirectActivity(MerchatsmainDynmicListActivity.this,LoginActivity.class);
                        return;
                    }
                    if(dataBean.isDynamicpraiseState()){
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);
                        dataBean.setDynamicpraiseState(false);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count--;
                        ih.goood_tv.setText(count+"");
                        nofocus(userList.get(0).getUserId()+"",dataBean.getDynamicPraiseId()+"");
                    }else{
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
                        dataBean.setDynamicpraiseState(true);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count++;
                        ih.goood_tv.setText(count+"");
                        focus(userList.get(0).getUserId()+"",dataBean.getMerchantsDyId()+"");
                    }
                }
            });
            ih.goood_tv.setText(""+dataBean.getDynamicPraiseCount());
            ih.guest_tv.setText(""+dataBean.getGuestcount());
            if(TextUtils.isEmpty(dataBean.getMerchantsAvatarpath())){
                Glide.with(MerchatsmainDynmicListActivity.this)
                        .load(""+dataBean.getUserAvatarpath())
                        .asBitmap()
                        .animate(R.anim.fade_in)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                ih.juage_img_iv.setImageBitmap(resource);
                            }
                        });
            }else{
                Glide.with(MerchatsmainDynmicListActivity.this)
                        .load(""+dataBean.getMerchantsAvatarpath())
                        .asBitmap()
                        .animate(R.anim.fade_in)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                ih.juage_img_iv.setImageBitmap(resource);
                            }
                        });
            }
            if(TextUtils.isEmpty(dataBean.getMerchantsName())){
                ih.juage_img_tv.setText(""+dataBean.getUserName()+"");
            }else{
                ih.juage_img_tv.setText(""+dataBean.getMerchantsName()+"");
            }

            ih.datetime.setText(""+dataBean.getMerchantsCreatedate());
            ih.area.setText(""+dataBean.getMerchantsArea());
            ih.content.setText(""+dataBean.getMerchantsDyComment());

            ih.juage_img_iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("merchantsId",dataBean.getMerchantsId());
                    Tools.redirectActivity(MerchatsmainDynmicListActivity.this,StoreMainAllProduceActivity.class,map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(MerchatsmainDynmicListActivity.this,MerchatsActiveInfoActvitiy.class,map);
                }
            });

            ih.watchnum.setText(""+dataBean.getMerchantsDyLooknumber());
            //ih.address.setText(""+dataBean.getMerchantsAddress());
//            LatLng myselflatLng = new LatLng(mActivity.userLatitude,mActivity.userLongitude );
//            LatLng latLng = new LatLng(Double.parseDouble(dataBean.getMerchantsLatitude()),Double.parseDouble(dataBean.getMerchantsLongitude()));
//            int distance = (int) AMapUtils.calculateLineDistance(myselflatLng, latLng);
//            if (distance == 0) {
//                ih.location.setText("就在附近");
//            } else if (distance <= 5) {
//                ih.location.setText("不足5m");
//            } else {
//                if(distance>=1000){
//                    ih.location.setText("距离" + distance/1000 + "km");
//                }else{
//                    ih.location.setText("距离" + distance + "m");
//                }
//
//            }
        }


        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public LinearLayout all_ll;


            public ImageView goods_iv;

            public RelativeLayout goods_bt;
            public TextView goood_tv;
            public RelativeLayout guest_bt;
            public RelativeLayout watch_bt;
            public TextView guest_tv;
            public CircleImageView juage_img_iv;
            public  TextView juage_img_tv;
            public TextView datetime;
            public TextView location;
            public TextView area;
            public TextView content;
            public TextView watchnum;
            public TextView address;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                address=itemView.findViewById(R.id.address);
                all_ll = itemView.findViewById(R.id.all_ll);
                watchnum=itemView.findViewById(R.id.watchnum);
                goods_iv= itemView.findViewById(R.id.goods_iv);
                goods_bt=itemView.findViewById(R.id.goods_bt);
                goood_tv=itemView.findViewById(R.id.goood_tv);
                guest_bt=itemView.findViewById(R.id.guest_bt);
                watch_bt=itemView.findViewById(R.id.watch_bt);
                guest_tv=itemView.findViewById(R.id.guest_tv);
                juage_img_iv=itemView.findViewById(R.id.juage_img_iv);
                juage_img_tv=itemView.findViewById(R.id.juage_img_tv);
                datetime=itemView.findViewById(R.id.datetime);
                location=itemView.findViewById(R.id.location);
                area=itemView.findViewById(R.id.area);
                content=itemView.findViewById(R.id.content);
                watchnum=itemView.findViewById(R.id.watchnum);
            }
        }

        public void initRefresh(List<MerchatsmianDynimcDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchatsmianDynimcDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public  void focus(String userId,String merchantsDyId){
            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("merchantsDyId",merchantsDyId);
            Xutils.POST(HttpUrl.chantpraiseAdd, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public  void  nofocus(String userId,String merchantsDyPraiseId){

            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("merchantsDyPraiseId",merchantsDyPraiseId);
            Xutils.POST(HttpUrl.chantpraiseDelete, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("*************************"+result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
    }



    public void query(int pagenow, final int merchantsId,final int userId) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsId", merchantsId + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.merchantdynmicbusinessById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                System.out.println("****************"+result);
                Gson gson = new Gson();
                MerchatsmianDynimcDomain domain = gson.fromJson(result, MerchatsmianDynimcDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),MerchatsmainDynmicListActivity.this));

                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow,final int merchantsId,final int userId) {

        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsId", merchantsId + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.merchantdynmicbusinessById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                MerchatsmianDynimcDomain domain = gson.fromJson(result, MerchatsmianDynimcDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),MerchatsmainDynmicListActivity.this));
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
              if(resultCode!=RESULT_OK){
                  return;
              }
            switch (requestCode){
                case FINSIH:
                    pulltofresh.autoRefresh();
                    break;
            }
    }
}
